package com.example.yichuangyun.mvvm.ui.activity.order.view;

import android.content.Context;
import android.util.Log;

import androidx.lifecycle.MutableLiveData;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.model.order.CreateOrderReqModel;
import com.example.yichuangyun.model.order.DefPackageModel;
import com.example.yichuangyun.model.order.DefPriceModel;
import com.example.yichuangyun.model.order.ProductReqModel;
import com.example.yichuangyun.model.order.SelectOrderInfoDataModel;
import com.example.yichuangyun.mvvm.base.BaseViewModel;
import com.example.yichuangyun.mvvm.di.retrofit.BaseModel;
import com.example.yichuangyun.mvvm.di.retrofit.BaseNetCallback;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.utils.treelist.SetShareBean;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.subscribers.ResourceSubscriber;

public class PlaceOrderViewModel extends BaseViewModel {

    public MutableLiveData<SelectOrderInfoDataModel> orderInfoDataModelMutableLiveData = new MutableLiveData<>();
    public MutableLiveData<List<SelectOrderInfoDataModel.OrderProductModel>> productListMutableLiveData = new MutableLiveData<>();
    private List<SelectOrderInfoDataModel.OrderProductModel> productList = new ArrayList<>();
    private final List<DefPackageModel> defPriceData = new ArrayList<>();
    private int productCount;
    private int reqCount;
    private int reqPriceCount;
    public MutableLiveData<String> createOrderSuccessMutableLiveData = new MutableLiveData<>();
    public final MutableLiveData<SetShareBean> treeData = new MutableLiveData<>();

    /**
     * 获取产品及基本信息
     */
    public void selectOrderInfo(String chanceId, Context context) {
        Map<String, Object> map = new HashMap<>();
        map.put("chanceid", chanceId);
        addSubscribe(mRetrofitHelper.selectOrderInfo(new Gson().toJson(map)).subscribeWith(new BaseNetCallback<SelectOrderInfoDataModel>() {

            @Override
            public void onSuccess(BaseModel<SelectOrderInfoDataModel> baseModel) {
                if (Constant.SUCCESS == baseModel.getCode()) {
                    if (baseModel.getData() != null) {
                        orderInfoDataModelMutableLiveData.setValue(baseModel.getData());
                        if (baseModel.getData().getPros() != null && baseModel.getData().getPros().size() > 0) {
                            productList = baseModel.getData().getPros();
                            productCount = productList.size();
                            for (SelectOrderInfoDataModel.OrderProductModel productModel : productList) {
                                getDefaultPriceResp(productModel.getId(), context);
                            }
                        }
                    }
                } else {
                    ToastHelper.show(baseModel.getMsg());
                }
            }
        }));
    }

    /**
     * 判断有无套餐，获取价格
     */
    public void getPrice(ProductReqModel reqModel) {
        addSubscribe(mRetrofitHelper.getPrice(new Gson().toJson(reqModel)).subscribeWith(new BaseNetCallback<DefPriceModel>() {

            @Override
            public void onSuccess(BaseModel<DefPriceModel> baseModel) {
                reqPriceCount++;
                if (Constant.SUCCESS == baseModel.getCode()) {
                    if (baseModel.getData() != null) {
                        for (SelectOrderInfoDataModel.OrderProductModel productModel : productList) {
                            if (reqModel.getProductId().equals(productModel.getId())) {
                                productModel.setPrice(baseModel.getData().getProductPrice());
                                if (baseModel.getData().getProductServiceAttrLists() != null) {
                                    for (SelectOrderInfoDataModel.OrderServiceModel orderServiceModel : productModel.getServiceList()) {
                                        for (DefPriceModel.ProductServiceAttrModel model : baseModel.getData().getProductServiceAttrLists()) {
                                            if (orderServiceModel.getId().equals(model.getServiceId())) {
                                                orderServiceModel.setServiceCostId(model.getId());
                                                // 设置价格
                                                for (SelectOrderInfoDataModel.OrderAttrsModel orderAttrsModel : orderServiceModel.getAttrs()) {
                                                    for (SelectOrderInfoDataModel.OrderMsgModel orderMsgModel : orderAttrsModel.getMsgs()) {
                                                        if (orderAttrsModel.getId() != null && orderAttrsModel.getId().equals(model.getAttrId()) && orderMsgModel.isSelect()) {
                                                            orderMsgModel.setPrice(model.getServiceAttrPrice());
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }

//                                    for (DefPriceModel.ProductServiceAttrModel model : baseModel.getData().getProductServiceAttrLists()) {
//                                        for (SelectOrderInfoDataModel.OrderServiceModel orderServiceModel : productModel.getServiceList()) {
//                                            if (orderServiceModel.getId().equals(model.getServiceId())) {
//                                                orderServiceModel.setServiceCostId(model.getId());
//                                            }
//
////                                            for (SelectOrderInfoDataModel.OrderAttrsModel orderAttrsModel : orderServiceModel.getAttrs()) {
////                                                for (SelectOrderInfoDataModel.OrderMsgModel orderMsgModel : orderAttrsModel.getMsgs()) {
////                                                    if (orderMsgModel.getId().equals(model.getAttrId()) && orderMsgModel.isSelect()) {
////                                                        orderMsgModel.setPrice(model.getServiceAttrPrice());
////                                                    }
////                                                }
////                                            }
//
//                                        }
//                                    }
                                }
                            }
                        }
                    }
                } else {
                    for (SelectOrderInfoDataModel.OrderProductModel productModel : productList) {
                        if (reqModel.getProductId().equals(productModel.getId())) {
                            productModel.setPrice(-1);
                        }
                    }
                }
                if (reqPriceCount == productCount) {
                    productListMutableLiveData.setValue(productList);
                    reqPriceCount = 0;
                }
//                Log.e("@@@@@@productList======", new Gson().toJson(productList));
            }

            @Override
            public void onError(String message) {
                super.onError(message);
                reqPriceCount = 0;
            }
        }));
    }

    /**
     * 获取默认套餐
     */
    public void getDefaultPriceResp(String id, Context context) {
        // 下单页面这一系列逻辑无法理解，各种拆分组装数据，自己捋逻辑吧，晕～～
        // 首先获取产品信息列表，得到默认的套餐，再设置套餐的默认价格，每点击再重新获取价格
        addSubscribe(mRetrofitHelper.getDefaultPriceResp(id).subscribeWith(new BaseNetCallback<List<DefPackageModel>>() {

            @Override
            public void onSuccess(BaseModel<List<DefPackageModel>> baseModel) {
                if (Constant.SUCCESS == baseModel.getCode()) {
                    if (baseModel.getData() != null && baseModel.getData().size() > 0) {
                        reqCount++;
                        defPriceData.addAll(baseModel.getData());
                        if (reqCount == productCount) {
                            for (SelectOrderInfoDataModel.OrderProductModel productModel : productList) {
                                // 创建ProductReqModel获取每个产品的价格
                                ProductReqModel reqModel = new ProductReqModel();
                                reqModel.setProductId(productModel.getId());
                                // -----------end
                                if (productModel.getServiceList() != null) {
                                    // 为ProductReqModel所用
                                    List<ProductReqModel.ProductServiceModel> selServiceList = new ArrayList<>();
                                    // -----------end
                                    for (SelectOrderInfoDataModel.OrderServiceModel serviceModel : productModel.getServiceList()) {
                                        // 为ProductReqModel所用
                                        ProductReqModel.ProductServiceModel productServiceModel = new ProductReqModel.ProductServiceModel();
                                        productServiceModel.setServiceName(serviceModel.getServiceName());
                                        productServiceModel.setServiceId(serviceModel.getId());
                                        selServiceList.add(productServiceModel);
                                        reqModel.setProductReqs(selServiceList);
                                        //-----------end
                                        if (serviceModel.getServiceType() == 1) {
                                            SelectOrderInfoDataModel.OrderAttrsModel orderAttrsModel = new SelectOrderInfoDataModel.OrderAttrsModel();
                                            orderAttrsModel.setAttName(context.getString(R.string.service_period));
                                            List<SelectOrderInfoDataModel.OrderMsgModel> orderMsgList = new ArrayList<>();
//                                            if (serviceModel.getCycles() != null) {
//                                                // 以前逻辑，改为以下
////                                                for (String s : serviceModel.getCycles()) {
////                                                    orderMsgList.add(new SelectOrderInfoDataModel.OrderMsgModel(s));
////                                                }
//                                                // -----start 现在：判断服务属性或周期性服务周期是否多个，多个默认不选中，单个默认选中
//                                                if (serviceModel.getCycles().size() == 1){
//                                                    orderMsgList.add(new SelectOrderInfoDataModel.OrderMsgModel(serviceModel.getCycles().get(0), true));
//                                                } else {
//                                                    for (String s : serviceModel.getCycles()) {
//                                                        orderMsgList.add(new SelectOrderInfoDataModel.OrderMsgModel(s));
//                                                    }
//                                                }
//                                                // -----end
//
//                                                orderAttrsModel.setMsgs(orderMsgList);
//                                                serviceModel.getAttrs().add(orderAttrsModel);
//                                            }

                                            if (serviceModel.getProductCycles() != null) {
                                                for (SelectOrderInfoDataModel.CyclesModel cyclesModel : serviceModel.getProductCycles()) {
                                                    orderMsgList.add(new SelectOrderInfoDataModel.OrderMsgModel(cyclesModel.getCycleValue()));
                                                }
                                                orderAttrsModel.setMsgs(orderMsgList);
                                                serviceModel.getAttrs().add(orderAttrsModel);
                                            }
                                        }
                                        // 为ProductReqModel所用
                                        List<String> remarkList = new ArrayList<>();
                                        // -----------end

                                        for (SelectOrderInfoDataModel.OrderAttrsModel attrsModel : serviceModel.getAttrs()) {
                                            for (SelectOrderInfoDataModel.OrderMsgModel msgModel : attrsModel.getMsgs()) {
                                                for (DefPackageModel priceModel : defPriceData) {
                                                    if (priceModel.getServiceType() == 1) {
                                                        if (priceModel.getServiceId().equals(serviceModel.getId()) && priceModel.getServiceAttrCycle() != null && priceModel.getServiceAttrCycle().equals(msgModel.getAttrMsg())) {
                                                            msgModel.setSelect(true);
                                                            break;
                                                        }
                                                    }
                                                    if (priceModel.getServiceId().equals(attrsModel.getServiceId()) && msgModel.getAttrMsg().equals(priceModel.getTerminalName())) {
                                                        msgModel.setSelect(true);
                                                        break;
                                                    }
                                                }

                                                if (msgModel.isSelect()) {
                                                    if (CommonUtil.isNumber(msgModel.getAttrMsg())) {
                                                        productServiceModel.setServiceAttrCycle(msgModel.getAttrMsg());
                                                    } else {
                                                        remarkList.add(msgModel.getAttrMsg());
                                                    }
                                                }
                                            }
//                                            // 为ProductReqModel所用
//                                            List<SelectOrderInfoDataModel.OrderMsgModel> msgList = attrsModel.getMsgs();
//                                            if (msgList != null) {
//                                                for (SelectOrderInfoDataModel.OrderMsgModel msgModel : msgList) {
//                                                    if (msgModel.isSelect()) {
//                                                        if (CommonUtil.isNumber(msgModel.getAttrMsg())) {
//                                                            productServiceModel.setServiceAttrCycle(msgModel.getAttrMsg());
//                                                        } else {
//                                                            remarkList.add(msgModel.getAttrMsg());
//                                                        }
//                                                    }
//                                                }
//                                            }
                                            // -----------end
                                        }
                                        // 为ProductReqModel所用
                                        productServiceModel.setRemarks(remarkList);
                                        // -----------end
                                    }
                                }
                                Log.e("@@@@@@@reqModel======", new Gson().toJson(reqModel));
                                getPrice(reqModel);
                            }
                        }
                    }
                }
            }
        }));
    }

    /**
     * 生成订单
     */
    public void createOrder(CreateOrderReqModel createOrderReqModel) {
        addSubscribe(mRetrofitHelper.createOrder(new Gson().toJson(createOrderReqModel)).subscribeWith(new BaseNetCallback<String>() {

            @Override
            public void onSuccess(BaseModel<String> baseModel) {
                if ("ok".equals(baseModel.getMsg()) || "success".equals(baseModel.getMsg())) {
                    EventBus.getDefault().post(new EventBusModel(Constant.refreshMainBusinessList));
                    createOrderSuccessMutableLiveData.setValue(baseModel.getMsg());
                } else {
                    ToastHelper.show(baseModel.getMsg());
                    mErrorData.setValue(baseModel.getMsg());
                }
            }

            @Override
            public void onError(String message) {
                super.onError(message);
                mErrorData.setValue(message);
                ToastHelper.show(message);
            }
        }));
    }

    public void getTreeList(String keyword) {
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("keyword", keyword);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        addSubscribe(mRetrofitHelper.getTreeData(requestData).subscribeWith(new ResourceSubscriber<SetShareBean>() {

            @Override
            public void onNext(SetShareBean setShareBean) {
                if (Constant.SUCCESS == setShareBean.getResult()) {
                    treeData.setValue(setShareBean);
                }
            }

            @Override
            public void onError(Throwable t) {
                mErrorData.setValue(t.getMessage());
            }

            @Override
            public void onComplete() {

            }
        }));
    }
}
